package com.zha.boss.mvc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zha.boss.client.mail.MailProperties;
import com.zha.boss.dao.entity.PayWay;
import com.zha.boss.dao.entity.UserInfo;
import com.zha.boss.dao.entity.UserPayConfig;
import com.zha.boss.dao.mapper.PayWayMapper;
import com.zha.boss.dao.mapper.UserInfoMapper;
import com.zha.boss.enums.resp.RespCode;
import com.zha.boss.events.domain.NoticeMailEvent;
import com.zha.boss.exceptions.BossException;
import com.zha.boss.mvc.service.MailService;
import jakarta.annotation.Resource;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @Author: zha
 * @CreateTime: 2024年09月19日 14:38
 */
@Service
public class MailServiceImpl implements MailService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private PayWayMapper payWayMapper;
    @Resource
    private ApplicationEventPublisher applicationEventPublisher;
    @Override
    public void sendSimpleMail(UserPayConfig userPayConfig) {
        // 查询支付方式
        QueryWrapper<PayWay> wrapper = new QueryWrapper<>();
        wrapper.eq("pay_product_code", userPayConfig.getPayProductCode());
        List<PayWay> payWayList = payWayMapper.selectList(wrapper);

        StringBuilder payWayName = new StringBuilder();
        payWayList.forEach(payWay -> {
            payWayName.append(payWay.getWayName()).append(" [").append(payWay.getWayCode()).append("]; ");
        });
        // 接收者邮箱
        UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("user_no", userPayConfig.getUserNo()));
        if (userInfo == null){
            throw new BossException(RespCode.USER_NOT_EXISTS);
        }
        // 使用事件机制,解耦合,将用户和支付产品通过邮件发送给商户
        // 商户号,  商户名称: appKey, appSecret,使用的支付产品code, 产品名称, 包含的支付方式
        StringBuilder mailText = new StringBuilder("");
        mailText.append("商户号: ").append(userPayConfig.getUserNo()).append("\n")
                .append("商铺名称: ").append(userPayConfig.getShopName()).append("\n")
                .append("appKey: ").append(userPayConfig.getAppKey()).append("\n")
                .append("appSecret: ").append(userPayConfig.getAppSecret()).append("\n")
                .append("支付产品code: ").append(userPayConfig.getPayProductCode()).append("\n")
                .append("支付产品名称: ").append(userPayConfig.getPayProductName()).append("\n")
                .append("支付方式列表:").append(payWayName.toString());
        MailProperties prop = new MailProperties();
        prop.setFrom("zhazhac@yeah.net");
        prop.setTo(new String[]{userInfo.getUserEmail()});
        prop.setSubject("支付产品配置通知");
        prop.setText(mailText.toString());
        NoticeMailEvent noticeMailEvent = new NoticeMailEvent(this, prop);
        applicationEventPublisher.publishEvent(noticeMailEvent);
    }
}
